/**
 * Live GPS Tracking Application
 * Speed graph
 *
 * Copyright 2009, Ivar Clemens
 */

package nl.ivarclemens.gpstrack.ui;

import nl.ivarclemens.gpstrack.track.MemTrack;
import nl.ivarclemens.gpstrack.nmea.PositionEvent;

import javax.microedition.lcdui.*;
import java.util.Vector;
import java.util.Enumeration;

public class SpeedWidget extends CustomItem implements PositionEvent {

    private double speedRange = 0.005;     // km/h
    private long timeRange = 20;      // sec

    private MemTrack track;

    public SpeedWidget(MemTrack track)
    {
        super("Speed");

        this.track = track;
    }

    public void posUpdate(long time, double lat, double lon, double ang, double vel)
    {
        this.repaint();
    }

    public void paint(Graphics g, int w, int h)
    {
        g.setColor(255, 255, 255);
        g.fillRect(0, 0, w, h);

        int lastIndex = track.numPoints();

        long endTime = track.getTime(lastIndex);
        long beginTime = endTime - timeRange;

        long nextTime = endTime;
        long nextTimeSpd = endTime;
        double nextSpeed = 0;

        for(int i = lastIndex; i > 0; i--) {
            long curTime = track.getTime(i - 1);
            long deltaTime = nextTime - curTime;

            if(curTime < beginTime) {
                throw new RuntimeException("" + curTime + "/" + beginTime + "/" + lastIndex);
                //break;
            }

            long curTimeSpd = curTime + (long) (deltaTime / 2);

            double curSpeed = track.getDistance(i) / deltaTime * 3.6;

            int x1 = (int) ((double) ((curTimeSpd - beginTime) * w) / timeRange);
            int x2 = (int) ((double) ((nextTimeSpd - beginTime) * w) / timeRange);

            int y1 = (int) ((double) (curSpeed * h) / speedRange);
            int y2 = 4 + (int) ((double) (nextSpeed * h) / speedRange);

            g.setColor(0, 0, 0);
            g.drawLine(x1, y1, x2, y2);

            g.setColor(0, 0, 255);
            g.fillTriangle(x1, y1, x2, 0, x2, y2);
            g.fillTriangle(x1, y1, x1, 0, x2, 0);

            nextSpeed = curSpeed;
            nextTimeSpd = curTimeSpd;
            nextTime = curTime;
        }
    }

    public int getMinContentWidth()
    {
        return 100;
    }

    public int getMinContentHeight()
    {
        return 100;
    }

    public int getPrefContentWidth(int width)
    {
        return 200;
    }

    public int getPrefContentHeight(int height)
    {
        return 200;
    }
}
